package com.example.backend.controller.address;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.dto.request.AddressDto;
import com.example.backend.dto.request.PageUserDto;
import com.example.backend.entitly.mysql.user.UserAddresses;
import com.example.backend.enums.ResultCodeEnum;
import com.example.backend.service.mysql.user.UserAddressesService;
import com.example.backend.utils.ResultJson;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/address")
@Tag(name = "地址管理")
public class AddressController {

    private final UserAddressesService userAddressesService;

    private Integer getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return (Integer) authentication.getPrincipal();
        }
        throw new UsernameNotFoundException(ResultCodeEnum.NOT_LOGIN.getMessage());
    }

    @Operation(summary = "获取地址列表")
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('user:address:read')")
    public ResultJson<?> getAddressList(@RequestBody PageUserDto pageUserDto) {
        Integer userId = getUser();
        pageUserDto.setUserId(userId);
        Page<UserAddresses> addressList = userAddressesService.getAddressList(pageUserDto);
        return ResultJson.success(addressList.getRecords());
    }

    @Operation(summary = "获取默认地址")
    @PostMapping("/default")
    @PreAuthorize("hasAuthority('user:address:read')")
    public ResultJson<?> getDefaultAddress() {
        Integer userId = getUser();
        UserAddresses defaultAddress = userAddressesService.getByDefault(userId);
        return ResultJson.success(defaultAddress);
    }


    @Transactional
    @Operation(summary = "添加地址")
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('user:address:add')")
    public ResultJson<?> addAddress(@RequestBody AddressDto addressDto) {
        Integer userId = getUser();
        addressDto.setUserId(userId);
        boolean b = userAddressesService.saveByAddress(addressDto);
        if (!b) {
            return ResultJson.fail(ResultCodeEnum.ADDRESS_ADD_FAILED.getCode(), ResultCodeEnum.ADDRESS_ADD_FAILED.getMessage());
        }
        return ResultJson.ok();
    }

    @Operation(summary = "删除地址", description = "删除地址")
    @DeleteMapping("/delete")
    @PreAuthorize("hasAuthority('user:address:delete')")
    public ResultJson<?> deleteAddress(@RequestParam Integer addressId) {
        Integer userId = getUser();
        boolean b = userAddressesService.removeByAddress(addressId, userId);
        if (!b) {
            return ResultJson.fail(ResultCodeEnum.ADDRESS_DELETE_FAILED.getCode(), ResultCodeEnum.ADDRESS_DELETE_FAILED.getMessage());
        }
        return ResultJson.ok();
    }

    @Operation(summary = "修改地址", description = "修改地址")
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('user:address:update')")
    public ResultJson<?> updateAddress(@RequestBody AddressDto addressDto) {
        Integer userId = getUser();
        if (ObjectUtils.isEmpty(addressDto)) {
            return ResultJson.fail(ResultCodeEnum.ADDRESS_UPDATE_FAILED.getCode(), ResultCodeEnum.ADDRESS_UPDATE_FAILED.getMessage());
        }
        addressDto.setUserId(userId);
        boolean b = userAddressesService.updateByAddress(addressDto);
        if (!b) {
            return ResultJson.fail(ResultCodeEnum.ADDRESS_UPDATE_FAILED.getCode(), ResultCodeEnum.ADDRESS_UPDATE_FAILED.getMessage());
        }
        return ResultJson.ok();
    }
}
